<template>
	<view class='equity_add'>
		<u-form :model="form" ref="uForm" label-width='200' label-align='left'>
			<view class='list'>
				<view class='f-c-sb title'>
					<view class='title_text'>基础信息</view>
				</view>
				<view>
          <u-form-item required label="权益卡名称" prop="rightsName">
            <u-input v-model="form.rightsName" input-align="right" placeholder="请输入名称"/>
          </u-form-item>
          <u-form-item required label="权益卡售价/元" prop="rightsPrice">
            <u-input type='digit' v-model="form.rightsPrice" input-align="right" placeholder="请输入金额/元"/>
          </u-form-item>
          <u-form-item required label="套餐卡成本" prop="rightsCost">
            <!-- <u-input type='number' v-model="form.rightsCost" input-align="right" placeholder="根据添加都礼包自动获取" disabled/> -->
            <u-input type='number' v-model="rightsCost" input-align="right" placeholder="根据添加都礼包自动获取" disabled/>
          </u-form-item>
          <u-form-item label="使用门店" required>
            <u-radio-group v-model="storeType">
              <u-radio
                  @change="radioChange"
                  name="0"
                  active-color='#007FFF'
              >
                当前门店
              </u-radio>
              <u-radio
                  @change="radioChange"
								name="1" 
								active-color='#007FFF'
							>
								选择其他门店
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item :label-position="labelPosition" label-width="150" label="选择门店" prop="joinStores" required  v-if="storeType==1">
						<view  style="width: 100%;" @click="goselectStore" v-if="form.joinStores.split(',').length&&form.joinStores.length!=0&&selectStore.length==0">已选择{{form.joinStores.split(',').length}}家门店</view>
						<view  style="width: 100%;" @click="goselectStore" v-else-if="selectStore.length!=0">已选择{{selectStore.length}}家门店</view>
						<view  style="width: 100%;"  @click="goselectStore" v-else>请选择门店</view>
					</u-form-item>
					<u-form-item label="使用说明" label-position='top'>
						<u-input 
							type="textarea" 
							:rows="2" 
							v-model="form.rightsContent" 
							resize="none"
							placeholder="请输入说明"
						>
						</u-input>
					</u-form-item>
				</view>
			</view>
			<view class='list'>
				<view class='f-c-sb title'>
					<view class='title_text'>包含礼包</view>
					<u-icon @click="deleteCard(form.rightsCouponDtos.length-1,1)" name="trash-fill" size="40"></u-icon>
				</view>
				<view>
					<u-form-item :required="true" label="权益卡类型">
						<view class='f-c'>
							<u-radio-group v-model="form.rightsType">
								<u-radio
									name="1"
									active-color='#007FFF'
								>
									卡券
								</u-radio>
							</u-radio-group>
							<view style='color:#007AFF;flex: 1;text-align: right;' @click='selCoupons'>
								<u-icon name="plus" color="#007FFF" size="30"></u-icon>新增卡券
							</view>
						</view>
					</u-form-item>
					<view v-for='(item,index) in form.rightsCouponDtos' :key='index'>
						<view v-if='index !== 0' class='f-c-sb coupon_title'>
							<view>新增卡券{{index}}</view>
							<u-icon @click="deleteCard(index,2)" name="trash-fill" size="40"></u-icon>
						</view>
						<u-form-item :required="true" label="优惠券类型">
							<view class='f-c-sb' style='width: 100%;'>
								<view v-if='!goodsText[index]' style='color:#C0C4CB;text-align:right;flex:1;' @tap='gotype(index)'>
									请选择优惠券使用类型
								</view>
								<view @tap='gotype(index)' v-if='goodsText[index]' style='text-align:right;flex:1;' > {{goodsText[index]}}</view>
								<u-icon name="arrow-right"></u-icon>
							</view>
						</u-form-item>
						<u-form-item :required="true" label="优惠券名称">
							<u-input type='text' v-model="item.name" input-align="right" placeholder="请输入名称" />
						</u-form-item>
						<u-form-item :required="true" label="优惠券金额">
							<u-input type='number' v-model="item.money" input-align="right" placeholder="请输入优惠券金额"/>
						</u-form-item>
						<u-form-item :required="true" label="使用条件">
							<u-input type='number' v-model="item.conditionMoney" input-align="right" placeholder="请输入满多少/元可以使用"/>
						</u-form-item>
						<u-form-item :required="true" label="数量">
							<u-input type='number' v-model="item.couponNum" input-align="right" placeholder="请输入数量" />
						</u-form-item>
					</view>
				</view>
			</view>
			<view class='list'>
				<view class='f-c-sb title'>
					<view class='title_text'>时间信息</view>
				</view>
				<view>
					<u-form-item :required="true" label="使用有效期" label-position='top'>
						<u-radio-group v-model="time">
							<u-radio
								name="0" 
								active-color='#007FFF'
							>
								<view class='f-c-sb'>
									<view>购买后有效天数</view>
									<u-input style='flex:1;margin-left:20rpx;' type='number' v-model="form.rightsTime" />
									<view style='color:#ccc'>0代表长期有效</view>
								</view>
							</u-radio>
						</u-radio-group>
					</u-form-item>
				</view>
			</view>
		</u-form>
		<view class='f-c-sa btn'>
      <u-button plain ripple size='medium' type="primary" @click='submit(2)'>预览效果</u-button>
      <u-button ripple size='medium' type="primary" @click='submit(1)'>完成创建</u-button>
    </view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
import {rightsEditEcho, rightsSave} from '@/api/marketing.js';
import {mapGetters} from 'vuex';

export default {
  name: 'equity_add',
  data() {
    return {
      form: {
        createStore: '',
        rightsName: '',
        rightsPrice: '',
        rightsCost: '',
        rightsContent: '',
        rightsType: '1',
					rightsTime:0,
					rightsCouponDtos:[{
						conditionMoney: '',   //使用条件，满多少元可以使用，保留两位小数，例如10.00
						couponNum: '',   //优惠券数量,多个用逗号分隔,数量排序对应优惠券id
						money: '',  //优惠券金额(元) ，保留两位小数，例如10.00
						name: "",  //优惠券名称
						serviceItems: "",//使用范围为2时，该字段为钣喷项目维护的工项id/商城商品id/指定车型id，多个共项逗号隔开  useArea=2必填
						type:'' ,  //优惠券类型(1-钣喷满减，2-洗车满减,3-保养满减,4-商城满减,5-美容满减)
						useArea: ''  //使用范围（1-全场通用，2-指定项目/商城商品可用/指定品牌.车系.车型）
					}],
				},
				rules: {
					rightsName: [
						{
							required: true,
							message: '请输入权益卡名称',
							trigger: 'blur,change'
						}
					],
					rightsPrice: [
						{
							required: true,
							message: '请输入金额',
							trigger: 'blur,change'
						}
					]
				},
				storeType:'0',
				storeViewText:'选择其他门店',
				time:'0',
				goodsText:[],
				goodsData:[],
				equitId:'',
			};
		},
		watch:{
			
		},
		onLoad(options){
			if(options.param) {
				this.equitId = JSON.parse(options.param).id;
				if (JSON.parse(options.param).id) {
				  this.form.rightsCouponDtos = []
				  this.getDetail()
				}
			}
		},
		computed: {
			...mapGetters(['userInfo','selectStore','selectStoreStr']),
			
			rightsCost(){
				let count = 0;
				this.form.rightsCouponDtos.forEach( item => {
					count = count +  item.money * item.couponNum
				})
				this.form.rightsCost = count.toFixed (2)
				return count.toFixed (2)
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			this.form.joinStores = this.userInfo.storeBasicId
			this.form.createStore = this.userInfo.storeBasicId
		},
		onShow(){
			var that = this
			if(this.storeType == 1 && this.selectStore.length){
				//其他门店且有已选
				var selStoreArr = [];
				this.selectStore.forEach((item,index) => {
					selStoreArr.push(item.storeId)
				})
				this.storeViewText = `已选${selStoreArr.length}家门店`
				selStoreArr = selStoreArr.join()
				this.form.joinStores = selStoreArr;
			}
			uni.$on('setCardData',data => {
				this.goodsData[data.pagelist] = data
				that.form.rightsCouponDtos[data.pagelist].serviceItems = data.goodsVal;
				that.form.rightsCouponDtos[data.pagelist].useArea = data.scope;
				that.form.rightsCouponDtos[data.pagelist].type = data.type.id;
				if(data.scope == 2){
					that.goodsText[data.pagelist] = data.type.name+'-'+'指定'+data.goodsVal.split(',').length+'件商品'
				}
				if(data.scope == 1){
					that.goodsText[data.pagelist] = data.type.name+'-'+'全场商品通用'
				}
			})
		},
		methods:{
			getDetail(){
				rightsEditEcho({id:this.equitId}).then( res => {
					var data = res.data;
					if(data.joinStores ==  this.userInfo.storeBasicId){
						this.storeType = '0'
					}
					else{
						this.storeType = '1'
					}
					this.form.createStore = data.createStore;
					this.form.rightsName = data.rightsName;
					this.form.rightsPrice = ''+data.rightsPrice;
					this.form.rightsCost = data.rightsCost;
					this.form.rightsContent = data.rightsContent;
					this.form.rightsType = data.rightsType;
					this.form.rightsTime = data.rightsTime;
					data.rightsGsEntities.forEach((item,index) => {
						if(item.useArea == 2){
							var str = item.typeName + '-指定'+(item.serviceItems || '').split(",").length+'件商品'
						}else if(item.useArea == 1){
							var str = item.typeName + '-全场商品通用'
						}
						this.goodsText.push(str)
						this.goodsData.push({
							goodsType: {name: '实物',value: '3'},
							goodsVal: item.serviceItems,
							pagelist: index,
							scope: 0,
							type: {
								id: item.type,
								name: item.typeName
							}
						})
						this.form.rightsCouponDtos.push({
							conditionMoney: item.conditionMoney,
							couponNum: item.couponNum,
							money: item.money,
							name: item.name,
							serviceItems: item.serviceItems,
							type:item.type,
							useArea: item.useArea
            })
          })
        })
      },
      gotype(index) {
        uni.navigateTo({
          // marketing/equity/goods?index=0&data=undefined
          url: '/marketing/equity/goods?index=' + index + '&data=' + (this.goodsData[index] ? JSON.stringify(this.goodsData[index]) : JSON.stringify({}))
        });
      },
      submit(type) {
        let that = this;
        if (that.storeType == 1) {
          if (!that.form.joinStores.length) {
            that.$refs.uToast.show({
              title: '请选择门店',
              type: 'default'
            })
            return
          }
        }
				var boo = function(){
					var boo = true;
					that.form.rightsCouponDtos.forEach( item => {
						Object.keys(item).forEach( ite => {
							if(!item[ite] && ite != 'serviceItems' && ite != 'type'){
								if( ite == 'useArea' ) var str = '请选择优惠券类型'
								if( ite == 'name' ) var str = '请输入优惠券名称'
								if( ite == 'money' ) var str = '请输入优惠券金额'
								if( ite == 'couponNum' ) var str = '请输入优惠券数量'
								if( ite == 'conditionMoney' ) var str = '请输入使用条件'
								that.$refs.uToast.show({
									title: str,
									type: 'default'
								})
								boo = false
							}
						})
					})
					return boo
				}
				if(!boo()) return
				that.$refs.uForm.validate(valid => {
					if (valid) {
            if (type == 2) {
              this.$put('equityDetail', that.form);

              this.$navigateTo('./detail', {});
              return;
            }
            rightsSave(that.form).then(res => {
              if (res.code == '1') {
                this.$put('isCreatStatus', '1')
                that.$refs.uToast.show({
                  title: '新增成功',
                  type: 'success',
                })
                that.$store.commit('setSelectStore', []);
                uni.switchTab({
                  url: '/pages/marketing/marketing'
								});
							}else{
								that.$refs.uToast.show({
									title: res.msg,
									type: 'default'
								})
							}
						});
						
					} else {
						console.log('验证失败');
					}
				});
			},
			radioChange(e){
				if(e == 0){  //当前门店
					this.form.joinStores = this.userInfo.storeBasicId
				}
				if(e == 1){  //当前门店
				this.form.joinStores=''
					this.goselectStore()
				}
			},
			goselectStore(){
				this.$store.commit('setSelectStoreStr',this.form.joinStores);
				this.$navigateTo('/pages/selectStore/selectStore', {});
			},
			selCoupons(){
				this.form.rightsCouponDtos.push({
					conditionMoney: '',   //使用条件，满多少元可以使用，保留两位小数，例如10.00
					couponNum: '',   //优惠券数量,多个用逗号分隔,数量排序对应优惠券id
					money: '',  //优惠券金额(元) ，保留两位小数，例如10.00
					name: "",  //优惠券名称
					serviceItems: "",//使用范围为2时，该字段为钣喷项目维护的工项id/商城商品id/指定车型id，多个共项逗号隔开  useArea=2必填
					type:'' ,  //优惠券类型(1-钣喷满减，2-洗车满减,3-保养满减,4-商城满减,5-美容满减)
					useArea: ''  //使用范围（1-全场通用，2-指定项目/商城商品可用/指定品牌.车系.车型）
				})
			},
			deleteCard(index,type){
				if(type==1&&this.form.rightsCouponDtos.length>1){
					 this.form.rightsCouponDtos.splice(index,1)
				}else if(type==1&&this.form.rightsCouponDtos.length==1||type==2&&this.form.rightsCouponDtos.length==1){
					this.$refs.uToast.show({
										title: '不能删除了',
										type: 'error'
									})
				}else if(type==2&&this.form.rightsCouponDtos.length>1){
					 this.form.rightsCouponDtos.splice(index,1)
				}
				
			}
		},
		onUnload(){
			this.$store.commit('setSelectStore' , []);
		}
	}
</script>

<style lang="less" scoped>
	.list{
		background-color: #fff;
		padding:13rpx 40rpx;
		margin:13rpx 22rpx;
		.title{
			font-size: 24rpx;
			line-height: 90rpx;
			.title_text{
				position: relative;
				font-size: 32rpx;
				font-weight: 700;
				text-align: left;
				color: #333333;
				border-bottom: 1px solid #efefef;
				line-height: 89rpx;
			}
			.title_text:after{
				position: absolute;
				width: 8rpx;
				top:30rpx;
				height: 32rpx;
				content: "";
				left: -20rpx;
				border-radius: 20rpx;
				background-color: #007FFF;
			}
		}
	}
	.coupon_title{
		font-weight: 600;
		line-height: 60rpx;
	}
	.btn{
		margin:50rpx 0;
	}
	
</style>
